package com.panda.service.impl;

import com.panda.annotation.SystemLog;
import com.panda.entity.po.LoginUser;
import com.panda.entity.vo.LoginUserVo;
import com.panda.entity.vo.UserInfoVo;
import com.panda.entity.vo.UserVo;
import com.panda.service.LoginService;
import com.panda.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Service("loginService")
public class LoginServiceImpl implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Override
    @SystemLog(businessName = "登陆")
    public RespondResult<LoginUserVo> login(UserVo userVo) {

        //前台传入User到spring security进行验证
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(userVo.getUsername(), userVo.getPasswordHash());
        //从spring security获取验证后的对象
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        //判断是否验证通过
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("用户名或密码错误");
        }

        //获取userid 生成token
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userid = loginUser.getUser().getId().toString();
        String jwt = JwtUtil.createJWT(userid);

        //把用户存入redis
        redisCache.setCacheObject("user:login:" + userid, loginUser, 24, TimeUnit.HOURS);
        UserInfoVo userInfoVo = BeanCopyUtil.copyBean(loginUser.getUser(), UserInfoVo.class);

        //返回token
        LoginUserVo loginUserVo = new LoginUserVo(jwt, userInfoVo);
        return RespondResult.okResult(loginUserVo);
    }

    @Override
    @SystemLog(businessName = "登出")
    public RespondResult logout() {
        Long userId = SecurityUtils.getUserId();
        redisCache.deleteObject("user:login:" + userId);
        return RespondResult.okResult();
    }
}
